package com.baidu.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baidu.entity.UserInfo;

public class JwtUtil {

    private static final String SECRET_KEY = "abc@123";

    //生成token
    public static String generateToken(int userId, String username, String userCode) {
        //获取到当前的时间
        DateTime now = DateTime.now();
        //获取当前时间之后的两小时
        DateTime expTime = now.offsetNew(DateField.HOUR, 2); // 令牌2小时后过期


        JSONObject payloadJson = new JSONObject();
        //存储token的一些数据   payload
        payloadJson.set("userId", userId);
        payloadJson.set("username", username);
        payloadJson.set("userCode", userCode);

        payloadJson.set(JWTPayload.ISSUED_AT, now);//token是什么时候颁发
        payloadJson.set(JWTPayload.EXPIRES_AT, expTime);//token什么时候过期

        String token = JWTUtil.createToken(payloadJson, SECRET_KEY.getBytes());

        return token;
    }

    public static boolean verifyToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        boolean verifyKey = jwt.setKey(SECRET_KEY.getBytes()).verify();
        boolean verifyTime = jwt.validate(0);
        return verifyKey && verifyTime;
    }

    public static UserInfo parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        JSONObject payloadJson = jwt.getPayloads();
        UserInfo user = new UserInfo();
        user.setUserId(payloadJson.getInt("userId"));
        user.setUserName(payloadJson.getStr("username"));
        user.setUserCode(payloadJson.getStr("userCode"));
        return user;
    }
}
